package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author WuHB
 * @date 2022/10/26 17:15
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/workOrderV2Pro")
public class WorkOrderController {

    @Resource
    private InitMenuHelp initMenuHelp;


    /**
     * 新工单初始化
     *
     * @param baseDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/menuInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String menuInit(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                MenuInitDTO menuInitDTO = new MenuInitDTO();
                BeanUtil.copyProperties(baseDTO, menuInitDTO, true);
                menuInitDTO.setAlias(XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias());
                initMenuHelp.menuInit(menuInitDTO);
                response = new XbbResponse<>(new BaseVO());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
